import config from "@/config"

export default {
	/**
	 * 函数节流
	 */
	throttle(func: Function, delay: number) {
		let timer: any
		return (...params: any[]) => {
			if (!timer) {
				timer = setTimeout(() => {
					func.apply(this, params)
					timer = null
				}, delay)
			}
		}
	},

	/**
	 * 函数防抖
	 */
	debounce(func: Function, delay) {
		let timer: any
		return (...params: any[]) => {
			clearTimeout(timer)
			timer = setTimeout(() => {
				func.apply(this, params)
			}, delay)
		}
	},

	/**
	 * 转化为文件服务器地址
	 * @param path 文件路径
	 * @returns 
	 */
	parse: (path: string | undefined) => {
		path ??= '/images/empty.png'
		return '/images/' + path
	},

	/**
	 * 图片源路径转base64
	 * @param path 图片路径
	 * @param quality 压缩的图片宽度
	 * @param type 图片类型
	 */
	ImageToBase64(path: string, quality: number, type: string) {
		return new Promise<string>((resolve, reject) => {
			const image = new Image()
			image.src = path
			// image.crossOrigin = 'anonymous'
			image.onload = () => {
				const x = image.width / quality
				const imageWidth = image.width / x
				const imageHeight = image.height / x
				const canvas = document.createElement('canvas')
				canvas.width = imageWidth
				canvas.height = imageHeight
				const context = canvas.getContext('2d')
				context.drawImage(image, 0, 0, image.width, image.height, 0, 0, imageWidth, imageHeight)
				const data = canvas.toDataURL(type === 'png' ? 'image/png' : 'image/jpeg')
				resolve(data)
			}
		})

	}

}